/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.worktime.service.export.xls;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.log4j.Logger;
import org.tnmk.common.util.file.FileMovingUtils;

/**
 *
 * @author tnmkhoi
 */
public abstract class ExcelExporter<D> {

  private Logger log = Logger.getLogger(this.getClass().getSimpleName());
  private static final String EXPORT_FOLDER_PATH = "export/";
  public static final File EXPORT_FILE = new File(EXPORT_FOLDER_PATH+"Sessions.xls");

  public void export(D data) throws WriteException {
    WritableWorkbook w = null;
    try {
      FileMovingUtils.createFileTree(EXPORT_FILE);
      w = Workbook.createWorkbook(EXPORT_FILE);
      WritableSheet s = w.createSheet("" + System.currentTimeMillis(), 0);
      export(s, data);
      w.write();
    } catch (IOException ex) {
      log.error("Cannot export to file: " + EXPORT_FILE.getAbsolutePath(), ex);
    } finally {
      if (w != null) {
        try {
          w.close();
        } catch (IOException ex) {
          log.error("Cannot close Workbook Writer", ex);
        }
      }
    }
  }

  abstract protected void export(WritableSheet s, D data) throws WriteException;

}
